package cn.nexd.app.collector.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import cn.nexd.app.collector.R;
import cn.nexd.app.collector.model.CollectConfig;
import cn.nexd.app.collector.presenter.db.TableContract;
import cn.nexd.app.collector.presenter.setting.SettingContract;
import cn.nexd.app.collector.presenter.setting.SettingPresenter;
import cn.nexd.app.collector.util.AnimUtil;


public class SettingActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener, SettingContract.View {
    private static final String TAG = "SettingActivity";
    private Switch beaconSwitch, wifiSwitch;
    private View beaconDetail, wifiDetail;
    private float[] foldAngle = new float[2];
    private float[] unfoldAngle = new float[2];
    private Button btnSubmit;
    private EditText etWifiSpeed, etWifiTime, etBeaconSpeed, etBeaconTime;
    private SettingContract.Presenter settingPresenter;
    private List<CollectConfig> collectConfigs = new ArrayList<>();
    private String userName;
    private String email;
    private TextView tvUserName, tvAboutUs, tvFileSetting;
    private LinearLayout llContainer;
    protected final static int REQUEST_CODE = 1;
    protected final static int RESULT_CODE = 2;

    //是否已经有选中的
    private int checkedPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        settingPresenter = new SettingPresenter(this);
        initData();
        initAnimParam();
        initView();
        bindData();
        bindListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    @Override
    protected void onStop() {
        super.onStop();


    }

    private void initData() {
        userName = getIntent().getStringExtra(SignInActivity.EXTRA_NAME);
        if (userName == null || TextUtils.isEmpty(userName)) {
            userName = "test";
        }

        email = getIntent().getStringExtra(SignInActivity.EXTRA_EMAIL);

        if (TextUtils.isEmpty(email)) {
            email = "test@nexdtech.com";
        }

    }

    private void bindData() {
        tvUserName.setText(userName);
    }

    private void bindListener() {
        beaconSwitch.setOnCheckedChangeListener(this);
        wifiSwitch.setOnCheckedChangeListener(this);
        btnSubmit.setOnClickListener(this);
        tvAboutUs.setOnClickListener(this);
        tvFileSetting.setOnClickListener(this);
    }

    private void initAnimParam() {
        foldAngle[0] = 90;
        foldAngle[1] = 0;
        unfoldAngle[0] = 0;
        unfoldAngle[1] = 90;
    }


    public void initView() {
        tvUserName = (TextView) findViewById(R.id.setting_collect_tv_username);
        tvAboutUs = (TextView) findViewById(R.id.setting_about_us);
        tvFileSetting = (TextView) findViewById(R.id.setting_file);
        Toolbar tlBar = (Toolbar) findViewById(R.id.setting_tl);
        llContainer = (LinearLayout) findViewById(R.id.setting_ll_container);
        btnSubmit = (Button) findViewById(R.id.setting_btn_submit);
        beaconSwitch = (Switch) findViewById(R.id.switch_beacon_setting);
        wifiSwitch = (Switch) findViewById(R.id.switch_wifi_setting);
        beaconDetail = findViewById(R.id.beacon_setting_detail);
        wifiDetail = findViewById(R.id.wifi_setting_detail);
        etWifiSpeed = (EditText) wifiDetail.findViewById(R.id.setting_collect_et_speed);
        etWifiTime = (EditText) wifiDetail.findViewById(R.id.setting_collect_et_time);
        etBeaconSpeed = (EditText) beaconDetail.findViewById(R.id.setting_collect_et_speed);
        etBeaconTime = (EditText) beaconDetail.findViewById(R.id.setting_collect_et_time);
        ////

        checkedPosition = beaconSwitch.getId();
        AnimUtil.foldAnim(beaconDetail, foldAngle);
    }

    @Override
    public void showToast(String msg) {
        Toast errorToast = Toast.makeText(SettingActivity.this, msg, Toast.LENGTH_SHORT);
        errorToast.setGravity(Gravity.CENTER, 0, 0);
        errorToast.show();
    }

    @Override
    public void startActivity() {
        Intent intent = new Intent(this, SelectBuildingActivity.class);
        intent.putExtra(TableContract.User.COLUMN_NAME_USERNAME, userName);
        intent.putExtra(TableContract.User.COLUMN_NAME_USEREMAIL, email);
        beaconSwitch.setChecked(false);
        wifiSwitch.setChecked(false);
        llContainer.setVisibility(View.GONE);
        startActivityForResult(intent, REQUEST_CODE);

    }

    // 每次选择采集方式前检测已选中项置为初始状态
    private void clearChecked() {
        if (checkedPosition == -1) {
            return;
        }
        if (checkedPosition == R.id.switch_beacon_setting) {
            AnimUtil.unFoldAnim(beaconDetail, unfoldAngle);
            beaconSwitch.setChecked(false);
        }
        if (checkedPosition == R.id.switch_wifi_setting) {
            AnimUtil.unFoldAnim(wifiDetail, unfoldAngle);
            wifiSwitch.setChecked(false);
        }
    }

    @Override
    public void printLog(String msg) {
        Log.d(TAG, "printLog: " + msg);
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            // TODO: 16/9/9  王旭, 修改,在开启参数项时,检查目标是否开启
            case R.id.switch_beacon_setting:
                clearChecked();
                if (isChecked) {
                    settingPresenter.ifCloseToOpen(SettingPresenter.CHECK_BLUETOOTH_STATE);
                    checkedPosition = buttonView.getId();
                    AnimUtil.foldAnim(beaconDetail, foldAngle);
                } else {
                    checkedPosition = -1;
                    AnimUtil.unFoldAnim(beaconDetail, unfoldAngle);
                }

                break;
            case R.id.switch_wifi_setting:
                clearChecked();
                if (isChecked) {
                    settingPresenter.ifCloseToOpen(SettingPresenter.CHECK_WIFI_STATE);
                    checkedPosition = buttonView.getId();
                    AnimUtil.foldAnim(wifiDetail, foldAngle);
                } else {
                    checkedPosition = -1;
                    AnimUtil.unFoldAnim(wifiDetail, unfoldAngle);
                }
                break;
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_btn_submit:
                checkCollectWay();
                //settingPresenter.submitMsg(collectConfigs);
                settingPresenter.checkPermission();
                break;
            case R.id.setting_about_us:
                startActivity(new Intent(this, AboutActivity.class));
                break;
            case  R.id.setting_file:
                startActivity(new Intent(this,FileManagerActivity.class));
        }
    }


    private void checkCollectWay() {
        String collectRate = "";
        String textOther = "";
        String collectWayOther = "";
        String collectWay = "";
        String cacheTime = "";
        String cacheTimeOther = "";
        if (beaconSwitch.isChecked() && !wifiSwitch.isChecked()) {
            collectRate = etBeaconSpeed.getText().toString();
            collectWay = beaconSwitch.getTag().toString();
            cacheTime = etBeaconTime.getText().toString();
        }
        if (wifiSwitch.isChecked() && !beaconSwitch.isChecked()) {
            collectRate = etWifiSpeed.getText().toString();
            collectWay = wifiSwitch.getTag().toString();
            cacheTime = etWifiTime.getText().toString();
        }
//        if (wifiSwitch.isChecked() && beaconSwitch.isChecked()) {
//            text = etWifiSpeed.getText().toString();
//            collectWay = wifiSwitch.getTag().toString();
//            textOther = etBeaconSpeed.getText().toString();
//            collectWayOther = beaconSwitch.getTag().toString();
//            cacheTime = etWifiTime.getText().toString();
//            cacheTimeOther = etBeaconTime.getText().toString();
//        }

        if (!TextUtils.isEmpty(cacheTime) && Integer.parseInt(cacheTime) < 500) {
            showToast("数据缓存时间过小");
            return;
        }

        if (!TextUtils.isEmpty(collectRate) && Integer.parseInt(collectRate) < 500) {
            showToast("采集间隔过小");
            return;
        }

        if (!TextUtils.isEmpty(cacheTime) && !TextUtils.isEmpty(collectRate) && Integer.parseInt(cacheTime) <= Integer.parseInt(collectRate)) {
            showToast("数据缓存时间不得小于等于采集间隔!");
            return;
        }

        if (!TextUtils.isEmpty(collectRate) && !TextUtils.isEmpty(cacheTime)) {
            collectConfigs.add(new CollectConfig(collectWay, Long.parseLong(collectRate), Long.parseLong(cacheTime)));
            if (!TextUtils.isEmpty(textOther) && !TextUtils.isEmpty(cacheTimeOther)) {
                collectConfigs.add(new CollectConfig(collectWayOther, Long.parseLong(textOther), Long.parseLong(cacheTimeOther)));
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: " + requestCode);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            collectConfigs.clear();
            llContainer.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void submitSetting() {
        settingPresenter.submitMsg(collectConfigs);
    }
}
